#include "UDPimg.h"

enum udpDataType : uint32_t{
    UDP_ID = 300,
    UDP_TAIL = 500
};

int IMAGEID = 0;

void sendImageUDP(const cv::Mat& image, const char* ip, int port) {
    int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    if (sockfd < 0) {
        std::cerr << "Socket creation failed" << std::endl;
        return;
    }

    struct sockaddr_in serverAddr;
    memset(&serverAddr, 0, sizeof(serverAddr));
    serverAddr.sin_family = AF_INET;
    serverAddr.sin_port = htons(port);
    inet_pton(AF_INET, ip, &serverAddr.sin_addr);

    size_t imgSize = image.cols * image.rows * 3;
    // printf("imgsize:%d\n", imgSize);
    // sendto(sockfd, &image.Myformat, sizeof(image.Myformat), 0, (struct sockaddr*)&serverAddr, sizeof(serverAddr));

    if(imgSize > 60000){
        uint8_t* data_ptr = image.data;
        int H_times = int(imgSize / 60000);
        if(H_times * 60000 < imgSize) H_times++;
        
        size_t frame_size {60000+8};
        uint8_t* frame = (uint8_t*)malloc(frame_size);

        for(int i = 0;i < H_times;i++){
            if(i == 0){
                enum udpDataType head = UDP_ID;
                uint32_t index = i;
                memcpy(frame, &head, sizeof(int));
                memcpy(frame+4, &index, sizeof(int));
                memcpy(frame+8, data_ptr, 60000);
                sendto(sockfd, frame, 60000+8, 0, (struct sockaddr*)&serverAddr, sizeof(serverAddr));
            }
            else if(i != H_times - 1){
                enum udpDataType head = UDP_ID;
                uint32_t index = i;
                memcpy(frame, &head, sizeof(int));
                memcpy(frame+4, &index, sizeof(int));
                memcpy(frame+8, data_ptr + 60000 * i, 60000);
                sendto(sockfd, frame, 60000+8, 0, (struct sockaddr*)&serverAddr, sizeof(serverAddr));
            }
            else{
                enum udpDataType head = UDP_TAIL;
                uint32_t index = i;
                memcpy(frame, &head, sizeof(int));
                memcpy(frame+4, &index, sizeof(int));
                memcpy(frame+8, data_ptr + i * 60000, imgSize - i * 60000);
                sendto(sockfd, frame, 60000+8, 0, (struct sockaddr*)&serverAddr, sizeof(serverAddr));
            }
        }
        free(frame);
    }
    IMAGEID = (IMAGEID+1)%20000;
    //image.saveMe("test.jpg", 100);
    close(sockfd);
}